
package com.faithbj.device.web.controller.admin;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.faithbj.device.model.configuration.Pager;
import com.faithbj.device.model.entity.DeviceInfo;
import com.faithbj.device.model.entity.Members;
import com.faithbj.device.service.DeviceInfoService;
import com.faithbj.device.service.MemberService;
import com.faithbj.device.support.filedownload.FileDownloadHandler;
import com.faithbj.device.support.fileupload.FileUploadHandlerSaveToLocalDisk;
import com.faithbj.device.support.fileupload.ScaleImage;

/**
 * @author jrn E-mail: rinanjin@gmail.com
 * 
 * @version 0.1 
 * 
 * <br/>创建时间：2012-5-15 下午06:59:13
 * 
 * <br/>类说明：仪器管理类
 */
@Controller
@RequestMapping("/faith/device")
public class AdminDeviceInfoController extends BaseAdminController
{
	private static final long serialVersionUID = 1L;

	private static Logger logger = LoggerFactory.getLogger(AdminDeviceInfoController.class);
	
	private final String OPERRATE_RETURN_URL = "faith/device/list";
	
	private final String VIEW = "/admin/device_info_view";
	
	private final String LIST = "/admin/device_info_list";
	
	private final String INPUT = "/admin/device_info_input";
	
	private final String DETAIL = "/admin/device_info_detail";
	
    @Value("${baseurl}")
	private String baseurl;
	
	@Resource(name="fileUploadHandlerSaveToLocalDisk")
	private FileUploadHandlerSaveToLocalDisk fileUploadHandlerSaveToLocalDisk;
	
	@Resource
	private MemberService memberService;
	
	@Resource(name="deviceInfoService")
	private DeviceInfoService deviceInfoService;
	
	@Resource(name="scaleImage")
	private ScaleImage scaleImage;
	
    @Resource
    private FileDownloadHandler fileDownloadHandler;
    
	@Resource
	public void setMemberService(MemberService memberService)
	{
		this.memberService = memberService;
	}

	@Resource(name="deviceInfoService")
	public void setDeviceInfoService(DeviceInfoService deviceInfoService)
	{
		this.deviceInfoService = deviceInfoService;
	}
	
	@Resource(name="scaleImage")
	public void setScaleImage(ScaleImage scaleImage)
	{
		this.scaleImage = scaleImage;
	}
	
	@RequestMapping(value = "/menu", method = RequestMethod.GET)
	public String menu(ModelMap map)
	{
		return "/admin/menu_info";
	}

	@RequestMapping(value = "/view")
	public String view(@ModelAttribute("pager") Pager pager, ModelMap map)
	{
		Pager pagerVal = deviceInfoService.findByPager(pager);
		map.put("pager", pagerVal);
		return VIEW;
	}
	
	@RequestMapping(value = "/list")
	public String list(DeviceInfo deviceInfo,Pager pager, ModelMap map)
	{
		if(pager.getKeywordList() == null)
		{
			pager.setKeywordList(new ArrayList<Object>());
			pager.setCompareTypeList(new ArrayList<String>());
			pager.setPropertyList(new ArrayList<String>());
		}
		pager = deviceInfoService.findByPager(pager, deviceInfo);
		map.put("pager", pager);
		map.put("deviceInfo", deviceInfo);
		return LIST;
			
	}
	
	@RequestMapping(value = "/reservelist")
	public String reservelist(DeviceInfo deviceInfo,Pager pager, ModelMap map)
	{
		Pager pagerVal = deviceInfoService.findByPager(pager, deviceInfo);
		map.put("pager", pagerVal);
		return "admin/reservation_list";
	}
	
	@RequestMapping(value = "/searchlist",method=RequestMethod.POST)
	public String searchlist(DeviceInfo deviceInfo,Pager pager, ModelMap map)
	{
		deviceInfo.handleBlankProperties();
		pager=deviceInfoService.findPagerByExample(deviceInfo, pager.getPageNumber(), pager.getPageSize());

		map.put("pager", pager);
		map.put("deviceInfo", deviceInfo);
		return "admin/reservation_list";
	}
	@RequestMapping(value = "/searchdevices",method=RequestMethod.POST)
	public String searchdevices(DeviceInfo deviceInfo,Pager pager, ModelMap map)
	{
		deviceInfo.handleBlankProperties();
		pager=deviceInfoService.findPagerByExample(deviceInfo, pager.getPageNumber(), pager.getPageSize());
		
		map.put("pager", pager);
		map.put("deviceInfo", deviceInfo);
		return "admin/device_info_list";
	}
	
	@RequestMapping(value = "/new")
	public String add(ModelMap map)
	{
		map.put("isAddAction", true);
		return INPUT;
	}
	
	@RequestMapping(value = "/detail/{id}")
	public String detail(@PathVariable("id") String id, ModelMap map)
	{
		DeviceInfo deviceInfo = deviceInfoService.get(id);
		map.put("deviceInfo", deviceInfo);
		return DETAIL;
	}
	
	@RequestMapping(value = "/image")
	public ResponseEntity<byte[]> image(@RequestParam("id") String id, HttpServletResponse response)
	{
		DeviceInfo deviceInfo = deviceInfoService.get(id);
		
		HttpHeaders headers = new HttpHeaders();
		if(StringUtils.contains(deviceInfo.getImagePath().toLowerCase(), ".jpg"))
			headers.setContentType(MediaType.IMAGE_JPEG);
		else if(StringUtils.contains(deviceInfo.getImagePath().toLowerCase(), ".gif"))
			headers.setContentType(MediaType.IMAGE_GIF);
		else
			headers.setContentType(MediaType.IMAGE_PNG);
        return new ResponseEntity<byte[]>(fileDownloadHandler.getFileBinary(deviceInfo.getImagePath()), headers, HttpStatus.OK);
		
		
		
//		try 
//		{
//			DeviceInfo deviceInfo = deviceInfoService.get(id);
//			ServletOutputStream outStream = response.getOutputStream();
//			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
//			encoder.encode(scaleImage.generateImage(new File(deviceInfo.getImagePath()), 128, 128));
//			outStream.close();
//		}
//		catch (IOException e)
//		{
//			logger.error(e.getMessage());
//		}
	}
	
	@RequestMapping(value = "/edit/{id}")
	public String edit(@PathVariable("id") String id, ModelMap map)
	{
		DeviceInfo deviceInfo = deviceInfoService.get(id);
		// 管理员能编辑所有信息?、普通用户只能编辑自己录入的仪器信息
			// 
		map.put("deviceInfo", deviceInfo);
		map.put("isAddAction", false);
		return INPUT;
	}
	
	@RequestMapping("/delete/{id}")
	public String delete(@PathVariable("id") String id,ModelMap map)
	{
		Members member = getLoginMember();
		String currentUserName = member.getUsername();
		
		if(member != null)
		{
			DeviceInfo deviceInfo = deviceInfoService.get(id);
			String deviceInfoUserName = deviceInfo.getMember().getUsername();
			if("super".equals(currentUserName) || deviceInfoUserName.equals(currentUserName))
			{
				String imagePath = deviceInfo.getImagePath();
				if(imagePath != null)
				{
					File oldFile = new File(deviceInfoService.get(id).getImagePath());
					FileUtils.deleteQuietly(oldFile);
				}
				deviceInfoService.delete(id);
				map.put("redirectUrl", OPERRATE_RETURN_URL);
				return SUCCESS;
			}
			else
			{
				map.put("errorMessages", "您的权限不足!");
				return ERROR;
			}
		}
		map.put("errorMessages", "系统内部错误!");
		return ERROR;
	}
	
	@RequestMapping("/batchDelete")
	@ResponseBody
	public Map<String, String> batchDelete(@RequestParam String[] ids,ModelMap map)
	{
		Members member = getLoginMember();
		String currentUserName = member.getUsername();
		Map<String, String> resultMap = new HashMap<String, String>();
		if(member != null)
		{
			List<DeviceInfo> deviceInfos = deviceInfoService.get(ids);
			if(!"super".equals(member.getUsername()))
			{
				// 先有个权限校验的过程
				for(DeviceInfo deviceInfo : deviceInfos)
				{
					if(!deviceInfo.getMember().getUsername().equals(currentUserName))
					{
						resultMap.put("status", "error");
						resultMap.put("message", "批量删除操作失败");
						return resultMap;
					}
				}
			}
			for(DeviceInfo deviceInfo : deviceInfos)
			{
				String imagePath = deviceInfo.getImagePath();
				if(imagePath != null)
				{
					File oldFile = new File(deviceInfo.getImagePath());
					FileUtils.deleteQuietly(oldFile);
				}
				deviceInfoService.delete(deviceInfo.getId());
			}
			resultMap.put("status", "success");
			resultMap.put("message", "批量删除操作成功");
			return resultMap;
		}

		resultMap.put("status", "error");
		resultMap.put("message", "批量删除操作失败");
		return resultMap;
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(@RequestParam("file") MultipartFile multipartFile, DeviceInfo deviceInfo, ModelMap map)
	{
		if(multipartFile.getSize()> 0)
		{
			String imagePath = fileUploadHandlerSaveToLocalDisk.handleUpload(multipartFile, null, 3);
			deviceInfo.setImagePath(imagePath);
		}
		deviceInfoService.save(deviceInfo);
		map.put("redirectUrl", OPERRATE_RETURN_URL);
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
	public ModelMap save(@RequestParam("imgFile") MultipartFile imgFile)
	{
		ModelMap map =new ModelMap();
		if(imgFile.getSize()> 0)
		{
			String imagePath = fileUploadHandlerSaveToLocalDisk.handleUpload(imgFile, null, 3);
			map.put("error", 1);
			map.put("url", "/devices/faith/article/showimage?id=" + imagePath);
//			map.put("url", baseurl+"/faith/article/showimage?id=" + imagePath);
		}

		return map;
	}
	
	
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(@RequestParam("file") MultipartFile file,DeviceInfo deviceInfo, ModelMap map)
	{
		if(file.getSize() == 0)
		{
			String id = deviceInfo.getId();
			deviceInfo.setImagePath(deviceInfoService.get(id).getImagePath());
		}
		else
		{
			String id = deviceInfo.getId();
			if(deviceInfoService.get(id).getImagePath() != null)
			{
				File oldFile = new File(deviceInfoService.get(id).getImagePath());
				FileUtils.deleteQuietly(oldFile);
			}
			String fileType = null;
			String fileName = file.getOriginalFilename();
			if(fileName.indexOf(".") > 0)
			{
				fileType = fileName.substring(fileName.indexOf(".") + 1);
			}
			String imagePath = fileUploadHandlerSaveToLocalDisk.handleUpload(file, fileType, 1);
			deviceInfo.setImagePath(imagePath);
			
		}
		
		deviceInfoService.update(deviceInfo);
		
		map.put("redirectUrl", OPERRATE_RETURN_URL);
		return SUCCESS;
	}
}
